package com.zzyl.serve.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 16701
 */
@Component
public class WechatUtil {
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    private static final String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";



    public String getOpenId(String code){
        //封装请求参数对象，请求小程序服务端获取openId
        //封装请求对象
        Map<String,Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //发送轻请求从响应结果中获取用户的openID
        String response = HttpUtil.get(OPEN_ID_URL,map);
        JSONObject responseObj = JSONUtil.parseObj(response);
        if(Objects.nonNull(responseObj.getInt("errcode"))){
            throw new BaseException(responseObj.getStr("errmsg"));
        }
        return responseObj.getStr("openid");
    }
    public String getPhone(String phoneCode){
        Map<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);
        String response = HttpUtil.post(PHONE_URL + getToken(), JSONUtil.toJsonStr(map));
        JSONObject responseObj = JSONUtil.parseObj(response);
        if(responseObj.getInt("errcode") != 0){
            throw new BaseException(responseObj.getStr("errmsg"));
        }
        JSONObject phoneInfo = responseObj.getJSONObject("phone_info");
        return phoneInfo.getStr("phoneNumber");
    }

    /**
     * 获取access_token
     */
    public String getToken(){
        Map<String,Object> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid",appid);
        map.put("secret",secret);
        String response = HttpUtil.get(TOKEN_URL, map);
        JSONObject responseObj = JSONUtil.parseObj(response);

        return responseObj.getStr("access_token");
    }

}
